#include "listen_thread.h"
#include "tb_interface.h"
#include <QByteArray>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <atomic>
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

reciv_thread::reciv_thread(QObject *parent)
	:QThread(parent)
{

}

std::atomic<bool> bfinished;

void reciv_thread::run()
{
	bfinished = false;
	using namespace TASKBUS;
	std::vector<unsigned char> vec_readbuf;
	static const size_t header_sz = sizeof(subject_package_header);
	while (false==bfinished)
	{
		size_t len = pull_subject(&vec_readbuf);
		if (len <= header_sz)
			continue;
		subject_package_header *pHeader = (subject_package_header *) vec_readbuf.data();
		if (false==is_valid_header(*pHeader))
		{
			bfinished = true;
			continue;
		}
		if ( is_control_subject(*pHeader))
		{
			//收到命令进程退出的广播消息,退出
			//quit command Recieved
			if (strstr(control_subject(vec_readbuf).c_str(),"function=quit;")!=nullptr)
			{
				bfinished = true;
				qDebug()<<"Quit!";
				emit sig_quit();
			}
		}
		else
		{
			QByteArray arrHead((char *) vec_readbuf.data(),sizeof(subject_package_header)+pHeader->data_length);
			emit new_package(arrHead);
		}
	}
	return ;
}

